package com.zsj.util;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.UUID;

/**
 * ID 生成器
 */
@Slf4j
@Getter
@Component
public class IDGenerator {

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getSpddSeqNo() {
        Random rand = new Random();
        int randomNumber = rand.nextInt(1000);
        return DateUtil.getSpddTimestamp() + String.format("%03d", randomNumber);
    }

    public String getOrderId() {
        return "ZSJ" + DateUtil.getCurrentDay() + snowflakeIdWorker.nextId();
    }

    private SnowflakeIdWorker snowflakeIdWorker;

    @PostConstruct
    public void init() {
        Long workId = getWorkId();
        Long dataCenterId = this.getDataCenterId();
        this.snowflakeIdWorker = new SnowflakeIdWorker(workId, dataCenterId);
    }


    private Long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            log.info("SnowflakeIdWorker hostAddress:{}", hostAddress);
            int[] arrInt = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : arrInt) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }

    private Long getDataCenterId() {
        String hostName = SystemUtils.getHostName();
        log.info("SnowflakeIdWorker hostName:{}", hostName);
        if (StringUtils.isBlank(hostName)) {
            return RandomUtils.nextLong(0, 31);
        }
        int[] arrInt = StringUtils.toCodePoints(hostName);
        int sums = 0;
        for (int i : arrInt) {
            sums += i;
        }
        return (long) (sums % 32);
    }
}
